Dashboard Temp Share Shortlinks Frames API

HTMLify

(Leetcode) Find First and Last Position of Element in Sorted Array.cpp
Views: 1 | Author: cody
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
class Solution {
public:
    vector<int> searchRange(vector<int>& nums, int target) {
        
        int n = nums.size();
        if(n==0)return {-1,-1};
        //First Binary search to find first true for the condition nums[m] >= target
        int l = 0, h = n-1;
        while(l<h){
            int m = l + (h-l)/2;
            
            if(nums[m]>=target){
                h = m;
            }
            else{
                l  = m+1;
            }
            
        }
        
        if(nums[l]!=target) return {-1,-1};//To check either target is present or not
        
        int startIndex = l ;
        
        //Second binary search to find last false for the condition nums[m]>target
        
        l = 0;
        h = n-1;
        
        while(l<h){
            
            int m = l + (h-l+1)/2;
            
            if(nums[m]>target){
                h = m;
            }
            else{
                l = m-1;
            }
            
        }
        
        int endIndex = l;
        
        return {startIndex,endIndex};
        
        
    }
};